// pages/realtime/realtime.js
const app = getApp();
const { deviceApi, getRealtimeAirQuality } = require('../../services/api');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    realtimeData: {
      score: 0,
      level: '',
      temperature: 0,
      humidity: 0,
      co2: 0,
      pm25: 0,
      formaldehyde: 0
    },
    isLoading: false,
    showError: false,
    errorMessage: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log('实时数据页面加载');
    this.fetchRealtimeData();
  },

  /**
   * 获取实时数据
   */
  fetchRealtimeData: function() {
    this.setData({ isLoading: true, showError: false });
    
    getRealtimeAirQuality().then(res => {
      if (res.code === 200) {
        this.setData({
          realtimeData: res.data,
          isLoading: false
        });
      } else {
        this.setData({
          showError: true,
          errorMessage: res.message || '获取数据失败',
          isLoading: false
        });
      }
    }).catch(err => {
      console.error('获取实时空气质量数据失败', err);
      this.setData({
        showError: true,
        errorMessage: '网络错误，请稍后再试',
        isLoading: false
      });
    });
  },

  /**
   * 刷新数据
   */
  refreshData: function() {
    this.fetchRealtimeData();
  },

  /**
   * 返回上一页
   */
  navigateBack: function() {
    wx.navigateBack({
      fail: function() {
        wx.switchTab({
          url: '../airquality/airquality'
        });
      }
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.fetchRealtimeData();
    wx.stopPullDownRefresh();
  },
  
  /**
   * 导出数据
   */
  exportData: function() {
    wx.showToast({
      title: '导出功能开发中',
      icon: 'none',
      duration: 2000
    });
  }
});